import gtk
import WindowTemplate
import Locations

class LocationWindow(WindowTemplate.WindowTemplate):
    """The location add/edit window"""
    
    def __init__(self,controller,location=None):
        """constuctor"""
        
        WindowTemplate.WindowTemplate.__init__(self,controller)
        self.location = location    # if edit mode this is the location to edit
        self.ddl_param_display_text = self.config.display_text['ddl param'] # shortcut
        self.params = {}            # the params hbox container
        self.create_window()
        if self.location:
            self.fill()
        else:
            self.add_param()        # add an empty parameter field
        
    def create_window(self):
        '''create and add widgets to the window'''
        
        if self.location:
            self.set_title("Location Settings")
        else:
            self.set_title("New Location")
        
        self.global_vbox = gtk.VBox()
        self.add(self.global_vbox)
        
        #Name
        self.lbl_name = gtk.Label("Name :")
        self.tb_name = gtk.Entry(max=25)
        self.add_validator(self.tb_name,'REGEX_NAME',False)
        self.set_focus(self.tb_name)
        self.global_vbox.pack_start(self.build_hbox((self.lbl_name,self.tb_name)),False)
        
        #Automount
        self.cb_automount = gtk.CheckButton("Automount")
        self.global_vbox.pack_end(self.build_hbox((self.cb_automount,)),False)
        
        #Submit Button
        submit_button = gtk.Button(None,gtk.STOCK_APPLY)
        submit_button.connect("clicked",self.submit)
        self.global_vbox.pack_end(submit_button,False)
        
        #Add Param Button
        add_param_button = gtk.Button("+")
        add_param_button.connect("clicked",self.add_param_callback)
        self.global_vbox.pack_end(add_param_button,False)
        
        self.show_all()
    
    def add_param(self,param_type=None,param_value=''):
        '''add a param field (ddl + entry + delete button)'''
        
        # create widgets
        ddl_param = gtk.combo_box_new_text()
        tb_param = gtk.Entry()
        tb_param.set_text(param_value)
        btn_remove = gtk.Button(None,gtk.STOCK_DELETE)
        hbox = self.build_hbox((ddl_param,tb_param,btn_remove))
        
        # store hbox to allow remove and validation  
        self.params[hbox] = (ddl_param,tb_param)
        
        ddl_param.connect('changed',self.change_param_type_callback,hbox)
        btn_remove.connect('clicked',self.remove_param_callback,hbox)
        
        # fill the param type ddl
        for param in ('public','dns','local'):
            ddl_param.append_text(self.ddl_param_display_text[param])
        self.__set_param(ddl_param,param_type)
        self.global_vbox.pack_start(hbox,False)
        self.global_vbox.show_all()
    
    def fill(self):
        '''fill all the fields and create params for the edited location'''
        
        self.tb_name.set_text(self.location.name)
        self.cb_automount.set_active(self.location.automount)
        for param in self.location.dns:
            self.add_param('dns',param)
        for param in self.location.public_addr:
            self.add_param('public',param)
        for param in self.location.local_addr:
            self.add_param('local',param)
        if not len(self.params):    # add an empty field if no one exist
            self.add_param()
            
    def __set_param(self,ddl,param):
        '''set the gived param in the given ddl'''
        
        ddl.set_active(0)
        if param:
            model = ddl.get_model()
            iter = model.get_iter_root()
            while iter != None:
                if model.get_value(iter,0) == self.ddl_param_display_text[param]:
                    ddl.set_active_iter(iter)
                    break
                iter = model.iter_next(iter)
    
    def __get_param(self,ddl):
        '''return the gived ddl selected parameter type'''
        ddl_text = ddl.get_active_text()
        for key,value in self.ddl_param_display_text.iteritems():
            if value == ddl_text:
                return key
        
    def add_param_callback(self,widget):
        '''add param button callback here to absorb the widget parameter'''
       
        self.add_param()
    
    def remove_param_callback(self,widget,hbox):
        '''remove param button callback, remove param hbox and validator'''
        
        for item in hbox.get_children():
            if isinstance(item,gtk.Entry):
                self.remove_validator(item)
                break
        del self.params[hbox]
        self.global_vbox.remove(hbox)
    
    def change_param_type_callback(self,ddl,hbox):
        '''pamam ddl changed callback, modify corresponding validator'''
       
        if ddl.get_active_text() == self.ddl_param_display_text['dns']:
            regex = 'REGEX_DOMAIN'
        elif ddl.get_active_text() in (self.ddl_param_display_text['public'],self.ddl_param_display_text['local']):
            regex = 'REGEX_IP'
        self.add_validator(self.params[hbox][1],regex,True)
    
    def submit(self,*args):
        '''submit button callback, check if is valid, create or edit location, set/add the location'''
        
        if self.is_valid() :
            if not self.location:
                self.location = Locations.Location(self.locations.get_id())
            self.location.name = self.tb_name.get_text()
            self.location.automount = self.cb_automount.get_active()
            self.location.clear_params()
            for key,item, in self.params.iteritems():
                if item[1].get_text() != '' :
                    self.location.add_param(self.__get_param(item[0]),item[1].get_text())
            self.locations[self.location.id] = self.location # this cause Locations emit the set or add signal
            self.close()